package com.jtpay.sdk.manager;

import android.content.Context;

import com.jtpay.sdk.entity.UserModel;
import com.jtpay.sdk.gen.DaoMaster;
import com.jtpay.sdk.gen.DaoSession;
import com.jtpay.sdk.gen.UserModelDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Created by Administrator on 2017/8/29.
 */

public class DBManager {
    private static DBManager sInstance;
    private static Context sContext;
    private static UserModelDao mUserDao;
    public final static String dbName = "username.db";

    private DBManager() {

    }

    public static DBManager getInstance(Context context) {
        sContext = context;
        if (sInstance == null) {
            synchronized (DBManager.class) {
                if (sInstance == null) {
                    sInstance = new DBManager();
                    DaoMaster daoMaster = getDaoMaster(sContext);
                    DaoSession daoSession = daoMaster.newSession();
                    mUserDao = daoSession.getUserModelDao();
                }
            }
        }
        return sInstance;
    }

    private static DaoMaster getDaoMaster(Context context) {
        DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, dbName, null);
        return new DaoMaster(helper.getWritableDatabase());
    }

    public long insertUser(UserModel user, List<UserModel> userModels) {
        UserModel model = hasModel(user, userModels);
        if (model != null) {
            mUserDao.update(model);
            return mUserDao.getKey(model);
        }
        return mUserDao.insert(user);
    }

    private UserModel hasModel(UserModel user, List<UserModel> userModels) {
        List<UserModel> models = userModels;
        for (UserModel model : models) {
            if (model.getUserName().equals(user.getUserName()) && model.getPlatformName().equals(user.getPlatformName())) {
                user.setId(model.getId());
                return user;
            }
        }
        return null;
    }

    public void insertUserList(List<UserModel> users) {
        if (users == null || users.isEmpty()) {
            return;
        }
        mUserDao.insertInTx(users);
    }

    public UserModel queryUserById(long userId) {
        if (userId < 0) {
            return null;
        }
        return mUserDao.load(userId);
    }

    public void deleteUser(UserModel user) {
        mUserDao.delete(user);
    }

    public void deleteAll() {
        mUserDao.deleteAll();
    }

    public void updateUser(UserModel user) {
        mUserDao.update(user);
    }

    public List<UserModel> queryUserList(String platformName) {
        QueryBuilder<UserModel> qb = mUserDao.queryBuilder().where(UserModelDao.Properties.PlatformName.eq(platformName));
        List<UserModel> list = qb.list();
        return list;
    }
}
